from django.db import models
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.models import CoreModel, SoftDeleteModel
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers

# drf专用过滤器模块
from django_filters import rest_framework as filters

from station.views.weldspot.hanqiang import Hanqiang

class Handian(CoreModel):

    xu_hao = models.TextField(verbose_name="序号", blank=True, null=True)
    station = models.TextField(verbose_name="station", blank=True, null=True)
    han_dian_bian_hao = models.TextField(verbose_name="焊点编号", blank=True, null=True)
    ling_bu_jian_hao= models.TextField(verbose_name="零部件号", blank=True, null=True)
    han_dian_xing_shi = models.TextField(verbose_name="焊点形式", blank=True, null=True)
    han_qiang_she_bei_bian_hao = models.TextField(verbose_name="焊枪设备编号", blank=True, null=True)


    class Meta:
        db_table = 'station_weldspot_handian'


class HandianModelSerializer(CustomModelSerializer):    
    han_qiang_xing_hao = serializers.SerializerMethodField()
    def get_han_qiang_xing_hao(self, obj):
        try:
            hanqiang = Hanqiang.objects.get(han_qiang_she_bei_bian_hao=obj.han_qiang_she_bei_bian_hao)
            if hanqiang:
                return str(hanqiang.han_qian_xing_hao)
            else:
                return 'None'
        except:
            return 'lookup error'

    class Meta:
        model = Handian
        fields = '__all__'


class HandianFilter(filters.FilterSet):
    station = filters.CharFilter(field_name='station', lookup_expr='icontains')
    han_dian_bian_hao = filters.CharFilter(field_name='han_dian_bian_hao', lookup_expr='icontains')
    ling_bu_jian_hao = filters.CharFilter(field_name='ling_bu_jian_hao', lookup_expr='icontains')
    han_qiang_she_bei_bian_hao = filters.CharFilter(field_name='han_qiang_she_bei_bian_hao', lookup_expr='icontains')
    class Meta:
        models = Handian
        fields = '__all__'


class HandianViewSet(CustomModelViewSet):
    values_queryset= Handian.objects.all()
    serializer_class = HandianModelSerializer
    filter_class = HandianFilter